package com.sogoodsoft.web.project;

import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.sogoodsoft.entity.account.User;
import com.sogoodsoft.entity.app.Organization;
import com.sogoodsoft.entity.app.SysClass;
import com.sogoodsoft.entity.project.Assessment;
import com.sogoodsoft.entity.project.PrjFile;
import com.sogoodsoft.entity.project.Project;
import com.sogoodsoft.service.account.AccountManager;
import com.sogoodsoft.service.app.OrganizationService;
import com.sogoodsoft.service.app.SysClassService;
import com.sogoodsoft.service.project.ProjectService;
import com.sogoodsoft.util.InfosysSecurityUtil;
import com.sogoodsoft.web.CrudActionSupport;
import com.sogoodsoft.web.WebConstants;
import com.opensymphony.xwork2.ActionContext;

@Namespace("/project")
@Results({ @Result(name = CrudActionSupport.RELOAD, location = "project.action", type = "redirect"),
        @Result(name = "ASSESSMENT", location = "/WEB-INF/content/project/assessment-result.jsp") })
public class ProjectAction extends CrudActionSupport < Project > {

    private static final long serialVersionUID = -1653204626115064950L;

    private ProjectService prjSer;

    private AccountManager accountManage;

    private OrganizationService orgSer;

    private SysClassService sysClaSer;

    private Long id;

    private Project project;

    private Long orgId;

    private Organization org;

    private Long sysClassId;

    private SysClass sysClass;

    private Long userId;

    private User user;

    private PrjFile[] prjFiles;

    private Page < Project > page = new Page < Project >(WebConstants.PAGE_SIZE);// 每页10条记录

    @Override
    public String delete() throws Exception {
        if (id != null) {
            project = prjSer.get(id);
            prjSer.delete(project);
        }

        return RELOAD;
    }

    /**
     * 非管理员，不能删除别人审报的项目
     */
    public void validateDelete() {
        project = prjSer.get(id);
        User currUser = InfosysSecurityUtil.getCurrentUser();
        if (currUser.getRoleNames().indexOf("管理员") < 0 && currUser.getId() != project.getUser().getId()) {
            this.addActionError(getText("project.action.delete.err"));
        }

    }

    @Override
    public String input() throws Exception {
        return INPUT;
    }

    /**
     * 查看项目审核结果
     * 
     * @return
     */
    public String result() {
        if (id != null)
            project = prjSer.get(id);
        return "ASSESSMENT";
    }

    @Override
    public String list() throws Exception {
        // InfosysUtils.encodingFilter(Struts2Utils.getRequest());
        List < PropertyFilter > filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        // 设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.DESC);
        }

        logger.debug("查询项目");
        page = prjSer.findPage(page, filters);
        return SUCCESS;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            project = prjSer.get(id);
        } else {
            project = new Project();
        }
        if (userId != null) {
            user = accountManage.getUser(userId);
            project.setUser(user);
        }
        if (sysClassId != null) {
            sysClass = sysClaSer.get(sysClassId);
            project.setSysClass(sysClass);
        }
        if (orgId != null) {
            org = orgSer.get(orgId);
            project.setOrganization(org);
        }

    }

    @Override
    public String save() throws Exception {
        prjFiles = (PrjFile[]) ActionContext.getContext().getSession().get("prjFiles");
        prjSer.save(project, prjFiles);
        ActionContext.getContext().getSession().remove("prjFiles");
        return RELOAD;
    }

    /**
     * 申报规则验证 不允许替下级单位申报
     */
    public void validateSave() {
        if (id != null) {
            project = prjSer.get(id);
        }

        if (sysClassId != null) {
            sysClass = sysClaSer.get(sysClassId);
            project.setSysClass(sysClass);
        }
        if (orgId != null) {
            org = orgSer.get(orgId);
            project.setOrganization(org);
        }
        int currOrg = Integer.parseInt(project.getOrganization().getType().trim());
        int target = Integer.parseInt(project.getSysClass().getValue().trim());
        if (currOrg < target) {
            this.addActionError(getText("project.action.save.err"));
            // "对不起，不允许替下级单位申报！"
        }

        /** 调用其它验证规则 **/

        // 非管理员，不允许修改他人申报的项目
        editOther();

        // 非管理员，不允许修改已进入审核程序的项目
        editOnAssessment();
    }

    /**
     * 非管理员，不允许修改他人申报的项目
     */
    public void editOther() {
        if (id == null)
            return;// 新建项目，无须验证
        User currUser = InfosysSecurityUtil.getCurrentUser();
        if (currUser.getRoleNames().indexOf("管理员") < 0
                && currUser.getId().intValue() != project.getUser().getId().intValue()) {
            this.addActionError(getText("project.action.save.edit_other.err"));
        }
    }

    /**
     * 非管理员，不允许修改已进入审核程序的项目
     */
    public void editOnAssessment() {
        if (id == null)
            return;// 新建项目，无须验证
        User currUser = InfosysSecurityUtil.getCurrentUser();
        if (currUser.getRoleNames().indexOf("管理员") < 0) {
            List < Assessment > list = project.getAssessments();
            for (Assessment a : list) {
                if (a.getSysClass() != null) {
                    this.addActionError(getText("project.action.save.edit_on_assessment.err"));
                    break;
                }
            }

        }
    }

    @Override
    public Project getModel() {
        return project;
    }

    public ProjectService getPrjSer() {
        return prjSer;
    }

    @Autowired
    public void setPrjSer(ProjectService prjSer) {
        this.prjSer = prjSer;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }

    public Page < Project > getPage() {
        return page;
    }

    public void setPage(Page < Project > page) {
        this.page = page;
    }

    public Long getOrgId() {
        return orgId;
    }

    public void setOrgId(Long orgId) {
        this.orgId = orgId;
    }

    public Long getSysClassId() {
        return sysClassId;
    }

    public void setSysClassId(Long sysClassId) {
        this.sysClassId = sysClassId;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public AccountManager getAccountManage() {
        return accountManage;
    }

    @Autowired
    public void setAccountManage(AccountManager accountManage) {
        this.accountManage = accountManage;
    }

    public OrganizationService getOrgSer() {
        return orgSer;
    }

    @Autowired
    public void setOrgSer(OrganizationService orgSer) {
        this.orgSer = orgSer;
    }

    public SysClassService getSysClaSer() {
        return sysClaSer;
    }

    @Autowired
    public void setSysClaSer(SysClassService sysClaSer) {
        this.sysClaSer = sysClaSer;
    }

    public Organization getOrg() {
        return org;
    }

    public void setOrg(Organization org) {
        this.org = org;
    }

    public SysClass getSysClass() {
        return sysClass;
    }

    public void setSysClass(SysClass sysClass) {
        this.sysClass = sysClass;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}
